package contents

import (
	"github.com/pkg/errors"
	"yizhuoyan/go-study/pdfgo/raw/objects/basicobject"
	"yizhuoyan/go-study/pdfgo/raw/objects/indirectobject"
)

var pagesTypeValueString = "/Pages"

type Pages struct {
	ObjectNumber        int
	ObjectVersionNumber int
	dic                 *basicobject.Dictionary
	Parent              *Pages
	Count               int
	Kids                *basicobject.Array
	locator             indirectobject.Locator
}

func (this *Pages) ParseRootFrom(obj *indirectobject.IndirectObject, locator indirectobject.Locator) error {
	dic := obj.MustGetDictionary()
	if !dic.HasKeyAndNameValue("/Type", pagesTypeValueString) {
		return errors.Errorf("非%s /Type", pagesTypeValueString)
	}
	if !dic.HasKey("/Count") {
		return errors.New("必须包含/Count")
	}
	this.Parent = nil
	this.dic = dic
	this.Count = dic.MustGetInteger("/Count").ValueInt()
	this.Kids = dic.MustGetArray("/Kids")
	this.locator = locator
	this.ObjectNumber = obj.ObjectNumber
	this.ObjectVersionNumber = obj.ObjectVersionNumber
	return nil
}
func (this *Pages) ParseFrom(parent *Pages, obj *indirectobject.IndirectObject) error {
	dic := obj.MustGetDictionary()
	if !dic.HasKeyAndNameValue("/Type", pagesTypeValueString) {
		return errors.Errorf("非%s /Type", pagesTypeValueString)
	}
	if !dic.HasKey("/Count") {
		return errors.New("必须包含/Count")
	}
	this.Parent = parent
	this.dic = dic
	this.Count = dic.MustGetInteger("/Count").ValueInt()
	this.Kids = dic.MustGetArray("/Kids")
	this.locator = parent.locator
	this.ObjectNumber = obj.ObjectNumber
	this.ObjectVersionNumber = obj.ObjectVersionNumber
	return nil

}
func (this *Pages) GetInheritableEntryValue(key string) basicobject.BasicObject {
	v := this.dic.Get(key)
	if v == nil {
		if this.Parent != nil {
			return this.Parent.GetInheritableEntryValue(key)
		}
	}
	return v
}

func (this *Pages) MustGetArray(s string) *basicobject.Array {
	rst := this.dic.MustGetArray(s)
	if rst == nil {
		if this.Parent != nil {
			return this.Parent.MustGetArray(s)
		}
	}
	return nil
}
